package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        roleMapper.deletePermissionByRoleId(id);
        roleMapper.deleteEmployeeByRole(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Role entity) {
        if (entity.getId() != null){
            roleMapper.deletePermissionByRoleId(entity.getId());
            roleMapper.updateByPrimaryKey(entity);
        }else {
            roleMapper.insert(entity);
        }
        List<Permission> permissions = entity.getPermissions();
        for (Permission permission : permissions) {
            roleMapper.insertPermissionByRoleId(permission.getId(),entity.getId());
        }
    }


    @Override
    public PageResult query(QueryObject qo) {
        int total = roleMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<?> rows = roleMapper.query4List(qo);
        return new PageResult(total,rows);
    }

    @Override
    public List<Long> selectRoleByEmpId(Long id) {
        return roleMapper.selectRoleIdByEmpId(id);
    }
}
